<template>
  <view class="orders-container">
    <!-- 自定义导航栏
    <navbar 
      title="我的订单" 
      right-text=""
      @goBack="goBack"
    /> -->

    <!-- 状态标签页 -->
    <view class="status-tabs">
      <view 
        v-for="(tab, index) in statusTabs" 
        :key="index"
        :class="['status-tab', { active: activeStatus === index }]"
        @click="switchStatus(index)"
      >
        <text class="tab-text">{{ tab }}</text>
        <view v-if="activeStatus === index" class="tab-indicator"></view>
      </view>
    </view>





    <!-- 订单列表 -->
    <view class="orders-list">
      <view v-if="filteredOrders.length === 0" class="empty-state">
        <view class="empty-icon">ℹ</view>
        <text class="empty-text">暂无数据</text>
      </view>
      
      <view 
        v-else
        v-for="(order, index) in filteredOrders" 
        :key="order.orderId"
        class="order-item"
        @click="viewOrderDetail(order)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="order-type">
            <text class="type-icon">{{ getOrderTypeIcon(order.orderType) }}</text>
            <text class="type-text">{{ order.orderType }}</text>
          </view>
          <view class="order-status">
            <text :class="['status-text', getStatusClass(order.orderStatus)]">
              {{ order.orderStatus }}
            </text>
          </view>
        </view>

        <!-- 订单内容 -->
        <view class="order-content">
          <view class="order-info">
            <text class="order-title">{{ order.orderTitle }}</text>
            <text class="order-description">{{ order.orderDescription }}</text>
            <view class="order-address">
              <text class="address-icon">📍</text>
              <text class="address-text">{{ order.orderAddress }}</text>
            </view>
          </view>
          <view class="order-amount">
            <text class="amount-symbol">¥</text>
            <text class="amount-value">{{ order.orderAmount }}</text>
          </view>
        </view>

        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="order-time">
            <text class="time-label">下单时间：</text>
            <text class="time-value">{{ formatTime(order.orderTime) }}</text>
          </view>
          <view class="order-actions">
            <button 
              v-if="order.orderStatus === '待付款'" 
              class="action-btn primary"
              @click.stop="payOrder(order)"
            >
              立即付款
            </button>
            <button 
              v-if="order.orderStatus === '待接单'" 
              class="action-btn secondary"
              @click.stop="cancelOrder(order)"
            >
              取消订单
            </button>
            <button 
              v-if="order.orderStatus === '待取货'" 
              class="action-btn secondary"
              @click.stop="contactRider(order)"
            >
              联系骑手
            </button>
            <button 
              v-if="order.orderStatus === '待送达'" 
              class="action-btn secondary"
              @click.stop="trackOrder(order)"
            >
              查看进度
            </button>
            <button 
              v-if="order.orderStatus === '已送达'" 
              class="action-btn primary"
              @click.stop="confirmDelivery(order)"
            >
              确认收货
            </button>
            <button 
              v-if="order.orderStatus === '已完成'" 
              class="action-btn secondary"
              @click.stop="reviewOrder(order)"
            >
              评价订单
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ordersApi } from '@/api/orders'
import type { Order, ApiResponse } from '@/types/api/orders'
import navbar from './navbar.vue'

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 状态标签页
const statusTabs = ref(['全部', '待付款', '待接单', '待取货', '待送达', '已送达', '已完成', '已过期'])
const activeStatus = ref(0)

// 订单数据
const orders = ref<Order[]>([])
const loading = ref(false)

// 根据状态筛选订单
const filteredOrders = computed(() => {
  console.log('计算筛选订单，当前状态索引:', activeStatus.value)
  console.log('当前状态:', statusTabs.value[activeStatus.value])
  console.log('所有订单:', orders.value)
  
  if (activeStatus.value === 0) {
    console.log('显示全部订单，数量:', orders.value.length)
    return orders.value
  }
  const status = statusTabs.value[activeStatus.value]
  const filtered = orders.value.filter(order => order.orderStatus === status)
  console.log(`筛选状态"${status}"的订单，数量:`, filtered.length)
  return filtered
})

// 获取订单数据
const fetchOrders = async () => {
  try {
    loading.value = true
    console.log('开始获取订单数据...')
    const response = await ordersApi.getOrders() as ApiResponse<Order[]>
    console.log('API响应:', response)
    
    if (response.success) {
      console.log('获取订单成功，数据:', response.data)
      orders.value = response.data
      console.log('设置订单数据后，orders.value:', orders.value)
    } else {
      console.error('API返回失败:', response.message)
      uni.showToast({
        title: response.message || '获取订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    uni.showToast({
      title: '获取订单失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}





// 切换状态标签页
const switchStatus = (index: number) => {
  activeStatus.value = index
  
  // 自动滚动到选中的标签
  nextTick(() => {
    const tabsContainer = document.querySelector('.status-tabs')
    const activeTab = document.querySelector(`.status-tab:nth-child(${index + 1})`)
    
    if (tabsContainer && activeTab) {
      const containerWidth = tabsContainer.clientWidth
      const tabLeft = (activeTab as HTMLElement).offsetLeft
      const tabWidth = (activeTab as HTMLElement).clientWidth
      
      // 计算滚动位置，使选中的标签居中显示
      const scrollLeft = tabLeft - (containerWidth / 2) + (tabWidth / 2)
      
      tabsContainer.scrollTo({
        left: Math.max(0, scrollLeft),
        behavior: 'smooth'
      })
    }
  })
}

// 获取订单类型图标
const getOrderTypeIcon = (type: string) => {
  const iconMap: { [key: string]: string } = {
    '代取快递': '📦',
    '代取外卖': '🍱',
    '代取须知': '📚',
    '骑手认证': '🏆',
    '闲置交易': '🛍️',
    '宿舍小店': '🏪'
  }
  return iconMap[type] || '📋'
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const classMap: { [key: string]: string } = {
    '待付款': 'status-pending',
    '待接单': 'status-waiting',
    '待取货': 'status-pickup',
    '待送达': 'status-delivery',
    '已送达': 'status-delivered',
    '已完成': 'status-completed',
    '已过期': 'status-expired'
  }
  return classMap[status] || ''
}

// 格式化时间
const formatTime = (time: Date | string | null) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 查看订单详情
const viewOrderDetail = (order: Order) => {
  uni.navigateTo({
    url: `/pages/orders/order-detail?orderId=${order.orderId}`
  })
}

// 支付订单
const payOrder = (order: Order) => {
  uni.showModal({
    title: '支付订单',
    content: `确定要支付订单 ${order.orderId} 吗？\n金额：¥${order.orderAmount}`,
    success: (res) => {
      if (res.confirm) {
        // 这里可以调用支付接口
        order.orderStatus = '待接单'
        order.paymentStatus = '已支付'
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        })
      }
    }
  })
}

// 取消订单
const cancelOrder = (order: Order) => {
  uni.showModal({
    title: '取消订单',
    content: `确定要取消订单 ${order.orderId} 吗？`,
    success: (res) => {
      if (res.confirm) {
        order.orderStatus = '已过期'
        uni.showToast({
          title: '订单已取消',
          icon: 'success'
        })
      }
    }
  })
}

// 联系骑手
const contactRider = (order: Order) => {
  uni.showModal({
    title: '联系骑手',
    content: `骑手姓名：${order.riderName || '未知'}\n骑手电话：${order.riderPhone || '未知'}`,
    confirmText: '拨打电话',
    success: (res) => {
      if (res.confirm && order.riderPhone) {
        uni.makePhoneCall({
          phoneNumber: order.riderPhone
        })
      }
    }
  })
}

// 查看进度
const trackOrder = (order: Order) => {
  uni.showModal({
    title: '订单进度',
    content: `下单时间：${formatTime(order.orderTime)}\n取货时间：${formatTime(order.pickupTime || null)}\n配送中...`,
    showCancel: false
  })
}

// 确认收货
const confirmDelivery = (order: Order) => {
  uni.showModal({
    title: '确认收货',
    content: `确定已收到订单 ${order.orderId} 的商品吗？`,
    success: (res) => {
      if (res.confirm) {
        order.orderStatus = '已完成'
        order.completeTime = new Date().toISOString()
        uni.showToast({
          title: '确认收货成功',
          icon: 'success'
        })
      }
    }
  })
}

// 评价订单
const reviewOrder = (order: Order) => {
  uni.showModal({
    title: '评价订单',
    content: `请对订单 ${order.orderId} 进行评价`,
    confirmText: '去评价',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '评价功能开发中',
          icon: 'none'
        })
      }
    }
  })
}

onMounted(() => {
  console.log('订单页面加载完成')
  // 页面加载时获取订单数据
  fetchOrders()
  
  // 添加触摸手势支持
  addTouchSupport()
})

// 添加触摸手势支持
const addTouchSupport = () => {
  const tabsContainer = document.querySelector('.status-tabs')
  if (!tabsContainer) return
  
  let startX = 0
  let startY = 0
  let isScrolling = false
  
  tabsContainer.addEventListener('touchstart', (e: Event) => {
    const touchEvent = e as TouchEvent
    startX = touchEvent.touches[0].clientX
    startY = touchEvent.touches[0].clientY
    isScrolling = false
  })
  
  tabsContainer.addEventListener('touchmove', (e: Event) => {
    const touchEvent = e as TouchEvent
    if (!isScrolling) {
      const deltaX = Math.abs(touchEvent.touches[0].clientX - startX)
      const deltaY = Math.abs(touchEvent.touches[0].clientY - startY)
      
      if (deltaX > deltaY && deltaX > 10) {
        isScrolling = true
      }
    }
  })
  
  tabsContainer.addEventListener('touchend', (e: Event) => {
    const touchEvent = e as TouchEvent
    if (isScrolling) {
      const deltaX = touchEvent.changedTouches[0].clientX - startX
      const threshold = 50
      
      if (Math.abs(deltaX) > threshold) {
        // 可以在这里添加左右滑动手势的逻辑
        console.log('检测到滑动手势:', deltaX > 0 ? '右滑' : '左滑')
      }
    }
  })
}
</script>

<style scoped>
.orders-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部标题栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 20rpx;
}

.action-icon {
  font-size: 32rpx;
  color: #666;
}



/* 状态标签页 */
.status-tabs {
  display: flex;
  background-color: #fff;
  padding: 0 20rpx;
  border-bottom: 1rpx solid #eee;
  overflow-x: auto;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
  /* 优化滚动体验 */
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch; /* iOS滚动优化 */
  /* 添加渐变遮罩提示可以滚动 */
  position: relative;
}

/* 隐藏Webkit浏览器的滚动条 */
.status-tabs::-webkit-scrollbar {
  display: none;
}

/* 添加左右渐变遮罩提示可以滚动 */
.status-tabs::before,
.status-tabs::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 40rpx;
  pointer-events: none;
  z-index: 1;
}

.status-tabs::before {
  left: 0;
  background: linear-gradient(to right, rgba(255, 255, 255, 0.8), transparent);
}

.status-tabs::after {
  right: 0;
  background: linear-gradient(to left, rgba(255, 255, 255, 0.8), transparent);
}



.status-tab {
  position: relative;
  padding: 20rpx 30rpx;
  white-space: nowrap;
  flex-shrink: 0; /* 防止标签被压缩 */
  cursor: pointer; /* 添加手型光标 */
  user-select: none; /* 防止文本被选中 */
  transition: all 0.2s ease; /* 添加过渡动画 */
}

/* 触摸反馈效果 */
.status-tab:active {
  transform: scale(0.95);
  opacity: 0.8;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .status-tabs {
    padding: 0 15rpx;
  }
  
  .status-tab {
    padding: 15rpx 20rpx;
  }
  
  .tab-text {
    font-size: 26rpx;
  }
}

.tab-text {
  font-size: 28rpx;
  color: #999;
  transition: all 0.3s ease;
  font-weight: 400;
}

.status-tab.active .tab-text {
  color: #f44336;
  font-weight: 500;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #f44336;
  border-radius: 2rpx;
  transition: all 0.3s ease;
}

/* 订单列表 */
.orders-list {
  padding: 20rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  font-size: 80rpx;
  color: #ccc;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 订单项 */
.order-item {
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-type {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.type-icon {
  font-size: 32rpx;
}

.type-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.order-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background-color: #f5f5f5;
}

.status-text {
  font-size: 24rpx;
  color: #666;
}

.status-text.status-pending {
  color: #ff9800;
}

.status-text.status-waiting {
  color: #2196f3;
}

.status-text.status-pickup {
  color: #9c27b0;
}

.status-text.status-delivery {
  color: #3f51b5;
}

.status-text.status-delivered {
  color: #4caf50;
}

.status-text.status-completed {
  color: #4caf50;
}

.status-text.status-expired {
  color: #f44336;
}

/* 订单内容 */
.order-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.order-info {
  flex: 1;
  margin-right: 20rpx;
}

.order-title {
  display: block;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
}

.order-description {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 15rpx;
  line-height: 1.4;
}

.order-address {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.address-icon {
  font-size: 24rpx;
  color: #999;
}

.address-text {
  font-size: 24rpx;
  color: #999;
}

.order-amount {
  text-align: right;
}

.amount-symbol {
  font-size: 24rpx;
  color: #f44336;
}

.amount-value {
  font-size: 36rpx;
  color: #f44336;
  font-weight: bold;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.order-time {
  display: flex;
  align-items: center;
}

.time-label {
  font-size: 24rpx;
  color: #999;
}

.time-value {
  font-size: 24rpx;
  color: #666;
}

.order-actions {
  display: flex;
  gap: 15rpx;
}

.action-btn {
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  border: none;
  outline: none;
}

.action-btn.primary {
  background-color: #f44336;
  color: #fff;
}

.action-btn.secondary {
  background-color: #f5f5f5;
  color: #666;
  border: 1rpx solid #ddd;
}
</style>